/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.lcm.metadata.common;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * @author zhaoleitr
 */
public class Which {
    public static File jarFile(final Class clazz) throws IOException {
        final String resourceName = clazz.getName().replace(".", "/") + ".class";
        URL resource = AccessController.doPrivileged(new PrivilegedAction<URL>() {
            @Override
            public URL run() {
                return clazz.getClassLoader().getResource(resourceName);
            }
        });
        if (resource == null) {
            throw new IllegalArgumentException("Cannot get bootstrap path from " + clazz + " class location, aborting");
        }

        if (resource.getProtocol().equals("jar")) {
            try {
                JarURLConnection c = (JarURLConnection) resource.openConnection();
                URL jarFile = c.getJarFileURL();
                try {
                    return new File(jarFile.toURI());
                } catch (URISyntaxException e) {
                    return new File(jarFile.getPath());
                }
            } catch (IOException e) {
                throw new IllegalArgumentException("Cannot open jar file " + resource, e);
            }
        } else
            throw new IllegalArgumentException("Don't support packaging " + resource + " , please contribute !");
    }
}
